/***

  Olive - Non-Linear Video Editor
  Copyright (C) 2019  Olive Team

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

***/

#include "colorfield.h"

#include <QColor>

#include "ui/colorbutton.h"
#include "nodes/node.h"
#include "undo/undo.h"

ColorField::ColorField(NodeIO* parent) :
  EffectField(parent, EffectField::EFFECT_FIELD_COLOR)
{}

QColor ColorField::GetColorAt(double timecode)
{
  return GetValueAt(timecode).value<QColor>();
}

QWidget *ColorField::CreateWidget(QWidget *existing)
{
  ColorButton* cb = (existing != nullptr) ? static_cast<ColorButton*>(existing) : new ColorButton();

  connect(cb, SIGNAL(color_changed(const QColor &)), this, SLOT(UpdateFromWidget(const QColor &)));
  connect(this, SIGNAL(EnabledChanged(bool)), cb, SLOT(setEnabled(bool)));

  return cb;
}

void ColorField::UpdateWidgetValue(QWidget *widget, double timecode)
{
  ColorButton* cb = static_cast<ColorButton*>(widget);

  cb->set_color(GetColorAt(timecode));
}

QVariant ColorField::ConvertStringToValue(const QString &s)
{
  return QColor(s);
}

QString ColorField::ConvertValueToString(const QVariant &v)
{
  return v.value<QColor>().name();
}

void ColorField::UpdateFromWidget(const QColor& c)
{
  KeyframeDataChange* kdc = new KeyframeDataChange(this);

  SetValueAt(GetParentRow()->ParentNode()->Time(), c);

  kdc->SetNewKeyframes();
  olive::undo_stack.push(kdc);
}
